/**
 * @ProjectName： naive-admin
 * @FileName： auto-lang.ts
 * @Description: // 处理多语言
 * @Author: ellwood
 * @date: 2024/1/15 - 8:00
 * @Version: V1.0.0
 */
import { defaultLocale, loadLanguageAsync } from '~/locales'

export const useAppLocale = createGlobalState(() =>
  useStorage('locale', defaultLocale),
)

export const useAutoLang = createGlobalState(() => {
  const appLocale = useAppLocale()

  const { locale, getLocaleMessage, t } = useI18n()
  const route = useRoute()
  const appStore = useAppStore()

  const setLanguage = async (lang: string) => {
    try {
      await loadLanguageAsync(lang)
      appLocale.value = lang
      locale.value = lang
      const title = route.meta.title
      if (title) {
        const localeTitle = t(title)
        document.title = `${localeTitle} - ${appStore.layout.title}`
      }
    }
    catch (e) {
      throw new Error(`Failed to load language: ${lang}`)
    }
  }

  const { isSupported, language } = useNavigatorLanguage()

  if (isSupported.value) {
    if (language.value && language.value !== defaultLocale) {
      setLanguage(language.value!).then(() => {
      })
    }

    watch(language, (lang) => {
      if (lang) {
        setLanguage(language.value!).then(() => {
        })
      }
    })
  }

  watch(appLocale, (lang) => {
    if (lang && lang !== locale.value) {
      setLanguage(lang).then(() => {
      })
    }
  })

  setLanguage(appLocale.value).then(() => {
  })

  const naiveLocale = computed(
    () => getLocaleMessage(appLocale.value).naiveUI || {},
  )

  return {
    naiveLocale,
  }
})
